//*********************************************************
//
//    Copyright (c) Microsoft. All rights reserved.
//    This code is licensed under the Apache License, Version 2.0.
//    THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
//    ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
//    IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
//    PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

namespace Microsoft.Research.ScientificWorkflow.TridentUtilities
{
    using System;
    using System.IO;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows.Data;
    using SD = System.Drawing;
    using WM = System.Windows.Media;

    using Microsoft.Research.DataLayer;
    using Type = System.Type;

    public class ImageToImageSource : IValueConverter
    {
        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            Namespace me = value as Namespace;
            if (me == null)
                return null;

            return ConvertImageToImageSource(me.Icon);
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotSupportedException();
        }

        #endregion

        public static WM.ImageSource ConvertImageToImageSource(SD.Image image)
        {
            if (image != null)
            {
                MemoryStream ms = new MemoryStream();
                image.Save(ms, SD.Imaging.ImageFormat.Png);
                WM.Imaging.PngBitmapDecoder pngDec =
                    new WM.Imaging.PngBitmapDecoder(ms, WM.Imaging.BitmapCreateOptions.None,
                        WM.Imaging.BitmapCacheOption.None);
                WM.ImageSource ret = pngDec.Frames[0];
                return ret;
            }
                
            return null;
        }
    }
}
